package NC115_栈和排序;

import java.util.*;


public class Solution {
    /**
     * 栈排序
     * @param a int整型一维数组 描述入栈顺序
     * @return int整型一维数组
     */
    public int[] solve (int[] a) {
        // write code here
        Stack<Integer> stack = new Stack<>();
        int n = a.length;
        int[] res = new int[n]; // 用来返回结果
        int cnt = 0;
        boolean[] flag = new boolean[n + 1];

        for (int i = 0; i < a.length; i++){
            stack.push(a[i]);
            flag[a[i]] = true;  // 压入一个数就把对应的数字标记为 true
            while (n > 0 && flag[n]){
                n--;
            }
            while (!stack.isEmpty() && n <= stack.peek()){
                res[cnt++] = stack.pop();
            }
        }

        while (!stack.isEmpty()){
            res[cnt++] = stack.pop();
        }
        return res;
    }
}
